﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Xml;
using StuMana.Services;
using MySql.Data.MySqlClient;

namespace StuMana.UI
{
    public partial class SchoolLate : Office2007Form
    {       
         #region Variables
        // datagridview parameters
        List<string>[] list;
        string[] columnName;
        string query;
        string[] columnNameReal;
        int page;
        int maxpage;
        static int rowperpage;

        private Services.DataviewService dataview = new Services.DataviewService();

        // Timer kiem tra thoi gian
        private System.Windows.Forms.Timer readTimer;

        // lay thoi gian
        DateTime dt = new DateTime();

        #endregion
        
        string ProPath;
        byte[] serial_buff = new byte[40];
        Services.SL025M rfid_reader = new Services.SL025M();
        Services.COM connect;
        private Bitmap image;
    //    private System.Windows.Forms.Timer readTimer;
        private string tag = "";
        private Boolean isSelect = false;
        private Services.student print_std = new Services.student();
        // get size of return byteArray
        private int size;

 // Initial COM connecting
        public void InitialConnect(StuMana.Services.COM conn)
        {
            connect = conn;
            rfid_reader.conn = conn.serialPort;
        }
  
        private bool flag = false;
        private bool co = false;
        private Font fontForAll = null;
        private StyleManager managerStyle=new DevComponents.DotNetBar.StyleManager();

        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name=reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());

                    if(style == "Bold")
                       fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(),size,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(),size,System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana=reader.Value.ToString();

                            if(stylemana=="Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if(stylemana=="Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if(stylemana=="Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if(stylemana=="Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if(stylemana=="Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if(stylemana=="Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if(stylemana=="Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if(stylemana=="Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }                
                    }
                } 
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for(int i=0;i<Controls[0].Controls[0].Controls[1].Controls.Count;i++) 
            {
                if (Controls[0].Controls[0].Controls[1].Controls[i] is LabelX)
                {
                    Controls[0].Controls[0].Controls[1].Controls[i].Font = fontForAll;
                }
            }
            styleManager1 = managerStyle;
        }

        public string GetTimeForClassNameWithSession(int session, string className, string cot)
        {
            string kq = "";
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                string query = "SELECT @a1 FORM Schedule WHERE Class = @a2 and Session = @a3 ";
                MySqlCommand cmd = new MySqlCommand(query, control.connection);              
                cmd.Parameters.AddWithValue("@a1", cot);
                cmd.Parameters.AddWithValue("@a2", className);
                cmd.Parameters.AddWithValue("@a3", session);

                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                kq = ds.Tables[0].Rows[0][0].ToString();                       
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }
            return kq;
        }
        public bool CheckLate(int session, string className, DateTime ngayGioDen)
        {
            string thu = ngayGioDen.DayOfWeek.ToString();
            string cotThu = "";
            if (thu == "Monday")
                cotThu = "T2";
            if (thu == "Tuesday")
                cotThu = "T3";
            if (thu == "Wednesday")
                cotThu = "T4";
            if (thu == "Thursday")
                cotThu = "T5";
            if (thu == "Friday")
                cotThu = "T6";
            if (thu == "Saturday")
                cotThu = "T7";

           // string gioSchedule = 

            return true;
        }

        public string GetTime(string className, int session)
        {
            string kq = "";
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT T2  FROM Schedule  WHERE  Class='" + className.ToString() + "' and Session =" + session.ToString() ;
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                if (ds.Tables[0].Rows.Count <1)
                    kq = "00:00:00";
                else
                    kq = ds.Tables[0].Rows[0][0].ToString();   
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }
            return kq;
        }

        public bool SoSanhTime(string time1, string time2)
        {
            return true;
        }

        private void LoadDanhSachSV(int type)
        {
            // type = 0 ;
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT studentinfo.TagID, Name, BirthDay, Gender, Class, time_inout.time, time_inout.Index  FROM studentinfo , time_inout  WHERE studentinfo.TagID=time_inout.TagID and  time_inout.InOut = " + type.ToString() + " and ( time_inout.Index = 1 or time_inout.Index = 2 )";
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);

                DataTable dtTemp = ds.Tables[0];
                DataTable dtResult = new DataTable();
                for (int i = 0; i < dtTemp.Columns.Count; i++)
                {
                    dtResult.Columns.Add(dtTemp.Columns[i].ColumnName.ToString());
                }

                for (int i = 0; i < dtTemp.Rows.Count; i++)
                {
                    string index = dtTemp.Rows[i]["Index"].ToString();
                    if (index == "1")
                    {
                        DateTime ngay = DateTime.Parse(dtTemp.Rows[i]["time"].ToString());
                        string timeNgay = ngay.TimeOfDay.ToString();// ("HH:mm:ss");
                        string timeTemp = GetTime(dtTemp.Rows[i]["Class"].ToString(), 1);
                        string[] latetime = timeTemp.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                        latetime[0] = latetime[0].Trim();
                        if (latetime[0] != "NONE")
                        {
                            DateTime t1 = DateTime.Parse(timeNgay);
                            DateTime t2 = DateTime.Parse(latetime[0]);

                            int value = TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay);
                            if (value == 1)
                            {
                                
                             //   dtResult.Rows.Add(dtTemp.Rows[i].ItemArray);
                                //0 => 6
                                dtResult.Rows.Add(dtTemp.Rows[i][0].ToString(),dtTemp.Rows[i][1].ToString(),DateTime.Parse(dtTemp.Rows[i][2].ToString()).ToString("MM/dd/yyyy"),dtTemp.Rows[i][3].ToString(),dtTemp.Rows[i][4].ToString(),dtTemp.Rows[i][5].ToString(), " Morning");
                                
                            }
                        }  
                    }
                    if (index == "2")
                    {
                        DateTime ngay = DateTime.Parse(dtTemp.Rows[i]["time"].ToString());
                        string timeNgay = ngay.TimeOfDay.ToString();// ("HH:mm:ss");
                        string timeTemp = GetTime(dtTemp.Rows[i]["Class"].ToString(), 2);
                        string[] time2 = timeTemp.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                        time2[0] = time2[0].Trim();

                        DateTime t1 = DateTime.Parse(timeNgay);
                        DateTime t2 = DateTime.Parse(time2[0]);

                        int value = TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay);
                        if (value == 1)
                        {
                          //  dtResult.Rows.Add(dtTemp.Rows[i].ItemArray);
                            dtResult.Rows.Add(dtTemp.Rows[i][0].ToString(), dtTemp.Rows[i][1].ToString(), DateTime.Parse(dtTemp.Rows[i][2].ToString()).ToString("MM/dd/yyyy"), dtTemp.Rows[i][3].ToString(), dtTemp.Rows[i][4].ToString(), dtTemp.Rows[i][5].ToString(), " Afternoon");
                        }                       
                    }

                }
                    // get latetime - get time 2 phu thuoc record index 1 , 2 
                    // so sanh voi
                   // dgvExDanhSach.DataSource = ds.Tables[0].DefaultView;
                dgvExDanhSach.DataSource = dtResult;      
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }
        }
    
        public SchoolLate()
        {
            InitializeComponent();
           schoolLate_initial();
        }

        // initials
        public void schoolLate_initial()
        {
            // timer 
            //timer setting
            readTimer = new System.Windows.Forms.Timer();
            readTimer.Interval = 1000;
            readTimer.Tick += new EventHandler(readTimer_Tick);
            readTimer.Enabled = true;

            // mysql command
            columnName = new string[] { "TagID", "Name", "Class","InOut_status" };
            columnNameReal = new string[] { "TagID", "Name", "Class", "InOut_status" };
            query = "SELECT TagID, Name, Class, InOut_status FROM studentinfo WHERE InOut_status=0";
            LoadDanhSachSV(1);           
        }

        /*
         * Timer handling
         */

        private void readTimer_Tick(object sender, EventArgs e)
        {
             dt = DateTime.Now;
            lblTime.Text = dt.ToLongTimeString();
            LoadDanhSachSV(1);
        }
     
        private void SchoolLate1_Load(object sender, EventArgs e)
        {
            ConfigSetting();
            LoadDanhSachSV(1);
            dtimeFilter.Value = DateTime.Today;
            if (dgvExDanhSach.Columns.Count > 0)
            {
                int w = dgvExDanhSach.Size.Width;
                int widthC = ((int)w / dgvExDanhSach.Columns.Count);

                for (int i = 0; i < dgvExDanhSach.Columns.Count; i++)
                {
                    dgvExDanhSach.Columns[i].Width = widthC;
                }
            }

            cmbClass.Items.Add("All Class");
            cmbClass.Items.Add("10A1");
            cmbClass.Items.Add("10A2");
            cmbClass.Items.Add("10A3");
            cmbClass.Items.Add("10A4");
            cmbClass.Items.Add("10A5");
            cmbClass.Items.Add("10A6");
            cmbClass.Items.Add("10A7");
            cmbClass.Items.Add("10A8");
            cmbClass.Items.Add("10A9");

            cmbClass.Items.Add("11A1");
            cmbClass.Items.Add("11A2");
            cmbClass.Items.Add("11A3");
            cmbClass.Items.Add("11A4");
            cmbClass.Items.Add("11A5");
            cmbClass.Items.Add("11A6");
            cmbClass.Items.Add("11A7");
            cmbClass.Items.Add("11A8");
            cmbClass.Items.Add("11A9");

            cmbClass.Items.Add("12A1");
            cmbClass.Items.Add("12A2");
            cmbClass.Items.Add("12A3");
            cmbClass.Items.Add("12A4");
            cmbClass.Items.Add("12A5");
            cmbClass.Items.Add("12A6");
            cmbClass.Items.Add("12A7");
            cmbClass.Items.Add("12A8");
            cmbClass.Items.Add("12A9");

            cmbClass.SelectedIndex = 0;
            co = true;
            flag = true;
        }

        private void SchoolLate1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void SchoolLate1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void SchoolLate1_Resize(object sender, EventArgs e)
        {
            if (dgvExDanhSach.Columns.Count > 0)
            {
                int w = dgvExDanhSach.Size.Width;
                int widthC = ((int)w / dgvExDanhSach.Columns.Count);
                if (co == true)
                {
                    for (int i = 0; i < dgvExDanhSach.Columns.Count; i++)
                    {
                        dgvExDanhSach.Columns[i].Width = widthC;
                    }
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string query = "SELECT s.TagID, Name, BirthDay, Gender, Account, time_inout.time  FROM studentinfo s , time_inout  WHERE InOut_status = 1  and time_inout.TagID = s.TagID ";
            if (txtTagID.Text != "")
            {
                query += " and s.TagID like N'%"+ txtTagID.Text+"%'";
            }
            if (txtName.Text != "")
            {
                query += " and s.Name like N'%"+ txtName.Text+"%'";
            }

            if (cmbClass.Text != "All Class")
            {
                query += " and s.Class = N'" + cmbClass.Text +"'";
            }         
            SearchDanhSachSV(query);           
        }

        private void SearchDanhSachSV(string query)
        {
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = query;
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                dgvExDanhSach.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (btnPause.Text == "Pause time")
            {
                readTimer.Stop();
                btnPause.Text = "Resume time";
            }
            else
            {
                readTimer.Start();
                btnPause.Text = "Pause time";
            }
        }

        private void LoadDataFromDate(DateTime input)
        {            
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
               query = "SELECT studentinfo.TagID, Name, BirthDay, Gender, Class, time, time_inout.index  FROM studentinfo , time_inout  WHERE studentinfo.TagID=time_inout.TagID  and Date(time_inout.Time) = '" + input.ToString("yyyy-MM-dd") + "' and (time_inout.index= 1 or time_inout.index = 2) ";
                if (txtTagID.Text != "")
                {
                    query += " and studentinfo.TagID like N'%" + txtTagID.Text + "%'";
                }
                if (txtName.Text != "")
                {
                    query += " and studentinfo.Name like N'%" + txtName.Text + "%'";
                }

                if (cmbClass.Text != "All Class")
                {
                    query += " and studentinfo.Class = N'" + cmbClass.Text + "'";
                }
          
                 cmd.CommandText = query;

                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);

                DataTable dtTemp = ds.Tables[0];
                DataTable dtResult = new DataTable();
                for (int i = 0; i < dtTemp.Columns.Count; i++)
                {
                    dtResult.Columns.Add(dtTemp.Columns[i].ColumnName.ToString());
                }

                for (int i = 0; i < dtTemp.Rows.Count; i++)
                {
                    string index = dtTemp.Rows[i]["Index"].ToString();
                    if (index == "1")
                    {
                        DateTime ngay = DateTime.Parse(dtTemp.Rows[i]["time"].ToString());
                        string timeNgay = ngay.TimeOfDay.ToString();// ("HH:mm:ss");
                        string timeTemp = GetTime(dtTemp.Rows[i]["Class"].ToString(), 1);
                        string[] latetime = timeTemp.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                        latetime[0] = latetime[0].Trim();
                        if (latetime[0] != "NONE")
                        {
                            DateTime t1 = DateTime.Parse(timeNgay);
                            DateTime t2 = DateTime.Parse(latetime[0]);

                            int value = TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay);
                            if (value == 1)
                            {
                           //     dtResult.Rows.Add(dtTemp.Rows[i].ItemArray);
                                dtResult.Rows.Add(dtTemp.Rows[i][0].ToString(), dtTemp.Rows[i][1].ToString(), DateTime.Parse(dtTemp.Rows[i][2].ToString()).ToString("MM/dd/yyyy"), dtTemp.Rows[i][3].ToString(), dtTemp.Rows[i][4].ToString(), dtTemp.Rows[i][5].ToString(), " Morning");
                            }
                        }
                    }
                    if (index == "2")
                    {
                        DateTime ngay = DateTime.Parse(dtTemp.Rows[i]["time"].ToString());
                        string timeNgay = ngay.TimeOfDay.ToString();// ("HH:mm:ss");
                        string timeTemp = GetTime(dtTemp.Rows[i]["Class"].ToString(), 2);
                        string[] time2 = timeTemp.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                        time2[0] = time2[0].Trim();

                        DateTime t1 = DateTime.Parse(timeNgay);
                        DateTime t2 = DateTime.Parse(time2[0]);

                        int value = TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay);
                        if (value == 1)
                        {
                          //  dtResult.Rows.Add(dtTemp.Rows[i].ItemArray);
                            dtResult.Rows.Add(dtTemp.Rows[i][0].ToString(), dtTemp.Rows[i][1].ToString(), DateTime.Parse(dtTemp.Rows[i][2].ToString()).ToString("MM/dd/yyyy"), dtTemp.Rows[i][3].ToString(), dtTemp.Rows[i][4].ToString(), dtTemp.Rows[i][5].ToString(), " Afternoon");
                        }
                    }
               }
                dgvExDanhSach.DataSource = dtResult;                         
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            LoadDataFromDate(dtimeFilter.Value);
        }       
    }
}
